#include "customtableview.h"

#include "commandexecutor.h"
#include "customsortfilterproxymodel.h"

#include <QKeyEvent>
#include <QMessageBox>
#include <QTableWidgetSelectionRange>

CustomTableView::CustomTableView(QAbstractItemModel * model, QWidget* parent) : QTableView(parent) {
    setModel(model);

    this->setFocusPolicy(Qt::FocusPolicy::ClickFocus);
    // # 设置整行选取模式
    this->setSelectionBehavior(QAbstractItemView::SelectRows);
    //冻结视图,作为第一列冻结的列
    // frozenTableView = new QTableView(this);

    // init();
}
#ifndef MYGLOBALFUNCTIONS_H
#define MYGLOBALFUNCTIONS_H
void a(){
    qDebug() << "=======>全局函数";
}
#endif
//! [constructor]

CustomTableView::~CustomTableView()
{
    delete frozenTableView;
}

//! [init part1]
void CustomTableView::init()
{
    frozenTableView->setModel(model());
    frozenTableView->setFocusPolicy(Qt::NoFocus);
    frozenTableView->verticalHeader()->hide();
    frozenTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    frozenTableView->setSelectionMode(QAbstractItemView::SingleSelection);//单选
    viewport()->stackUnder(frozenTableView);
    //! [init part1]

    //! [init part2]
    frozenTableView->setStyleSheet("QTableView { border: none;"
                                   "background-color: #8EDE21;"
                                   "selection-background-color: #999}"); //for demo purposes
    frozenTableView->setSelectionModel(selectionModel());
    for (int col = 1; col < model()->columnCount(); ++col)
        frozenTableView->setColumnHidden(col, true);

    frozenTableView->setColumnWidth(0, columnWidth(0) );

    frozenTableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    frozenTableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    frozenTableView->show();

    updateFrozenTableGeometry();

    setHorizontalScrollMode(ScrollPerPixel);
    setVerticalScrollMode(ScrollPerPixel);
    frozenTableView->setVerticalScrollMode(ScrollPerPixel);
}


//! [geometry]
void CustomTableView::updateFrozenTableGeometry()
{
    frozenTableView->setGeometry(verticalHeader()->width() + frameWidth(),
                                 frameWidth(), columnWidth(0),
                                 viewport()->height()+horizontalHeader()->height());
}
//! [geometry]


void CustomTableView::itemMovedSlot(int value, QString text) {
    // 处理信号
    qDebug() << "CustomTableView===>itemMovedSlot槽函数处理信号"<<value<<",text="<<text;

    QModelIndex currentIndex = this->currentIndex();
    int currentRow  = currentIndex.row();
    int currentColumn = currentIndex.column();
    // 计算下一个项的索引
    int nextRow = (currentRow + 1) % this->model()->rowCount();
     // 创建下一行的索引
    QModelIndex nextIndex = this->model()->index(nextRow, currentColumn);


    // 设置下一个项为当前选中项
    this->setCurrentIndex(nextIndex);

    // 假设listView是QListView对象，row是要选中项的行号，column是要选中项的列号
    // this->setCurrentIndex(this->model()->index(2, 0));

    this->setEditTriggers(QAbstractItemView::NoEditTriggers); // 禁止编辑


    //////////////// 设置和鼠标一样的选择样式没成功
    // 获取代理模型
    QSortFilterProxyModel *proxyModel = qobject_cast<QSortFilterProxyModel*>(this->model());
    if (!proxyModel) {
        return;
    }
    // 设置整行选择
    QItemSelection selection(proxyModel->index(nextRow, 0), proxyModel->index(nextRow, proxyModel->columnCount() - 1));
    // this->selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect);
}

void CustomTableView::itemMovedPrevSlot(int value,QString text) {
    // 处理信号
    qDebug() << "CustomListView--->itemMovedPrevSlot槽函数处理信号"<<value<<",text="<<text;

    QModelIndex currentIndex = this->currentIndex();
    int row = currentIndex.row();

    // 计算前一个项的索引
    int prevRow = (row - 1) % this->model()->rowCount();
    QModelIndex nextIndex = this->model()->index(prevRow, 0);


    // 设置前一个项为当前选中项
    this->setCurrentIndex(nextIndex);
}

void CustomTableView::getSelectedRowData()   {
    int currentRowNo = this->currentIndex().row();
    QModelIndexList list = this->selectedIndexes();
    qDebug()<<"getSelectedRowData-currentRowNo==="<<currentRowNo;


    // 获取并显示当前选中项
    QItemSelectionModel *selectedModel = this->selectionModel();
    if (selectedModel && selectedModel->hasSelection()) {
        QModelIndexList selected = selectedModel->selectedIndexes();
        if (!selected.isEmpty()) {
            const QModelIndex index = selected.first();
            QString selectedItem = index.data(Qt::DisplayRole).toString();
            // 输出当前选中项的数据
            qDebug() << "getSelectedRowData-Selected item:" << selectedItem;
        }
    }
}


void CustomTableView::keyPressEvent(QKeyEvent *event) {
    int key = event->key();
    Qt::KeyboardModifiers modifiers = event->modifiers();
    qDebug() << "CustomTableView-keyPressEvent-Key pressed:" << key ;
    if ((event->modifiers() == Qt::ControlModifier) || (event->modifiers() == Qt::AltModifier) || (event->modifiers() == Qt::ShiftModifier))
    {
        if(event->key() == Qt::Key_A){
        QMessageBox::aboutQt(NULL, "aboutQt");
        }

    }else{
        if (event->key() == Qt::Key_Tab) {
            // 获取当前选中项的索引
            QModelIndex currentIndex = this->currentIndex();
            int row = currentIndex.row();

            // 计算下一个项的索引
            int nextRow = (row + 1) % this->model()->rowCount();
            QModelIndex nextIndex = this->model()->index(nextRow, currentIndex.column());

            // 设置下一个项为当前选中项
            this->setCurrentIndex(nextIndex);
            qDebug() << "CustomTableView-当前选中行内容:" << model()->data(model()->index(nextRow, 0)).toString();
        }else    if (  event->key() == Qt::Key_Backtab) {
            // 获取当前选中项的索引
            QModelIndex currentIndex = this->currentIndex();
            int row = currentIndex.row();

            // 计算下一个项的索引
            int nextRow = (row - 1) % this->model()->rowCount();
            QModelIndex nextIndex = this->model()->index(nextRow, currentIndex.column());

            // 设置下一个项为当前选中项
            this->setCurrentIndex(nextIndex);
            qDebug() << "shift+tab==>CustomTableView-当前选中行内容:" << model()->data(model()->index(nextRow, 0)).toString();
        } else if (event->key() == Qt::Key_Space) {
            // 获取当前选中项的索引
            QModelIndex currentIndex = this->currentIndex();
            if (currentIndex.isValid()) {
                // 获取选中项的文本
                QString itemText = this->model()->data(currentIndex,0).toString();
                // 显示选中项的信息
                //QMessageBox::information(this, "Selected Item", "Selected: " + itemText);

                // 获取第四列的值
                QModelIndex fourthColumnIndex = model()->index(currentIndex.row(), 4); // 第5列索引
                QString value = model()->data(fourthColumnIndex).toString();

                // 显示值
                QMessageBox::information(this, "Selected Row", QString("第四列的值: %1").arg(value));
            }
        } else {
            QString qstr(key);
            //emit sig_input(&qstr);
            QTableView::keyPressEvent(event);
        }
    }
}

/**
 * 打印QTableView当前选中项
 * @brief Widget::onSelectedRow
 */
void CustomTableView::onSelectedRow(CustomSortFilterProxyModel *proxyModel)
{
    // 获取QSortFilterProxyModel的选择模型
    QItemSelectionModel *selectionModel = this->selectionModel();

    // 获取当前选中的行
    QModelIndexList selectedRows = selectionModel->selectedRows();

    int colNum = 0;
    // 遍历选中的行
    foreach (QModelIndex index, selectedRows) {
        //处理选中的行 方法一
        QString frequency = proxyModel->index(index.row(), colNum).data().toString();
        QString encoding = proxyModel->index(index.row(), ++colNum).data().toString();
        QString shortcut = proxyModel->index(index.row(), ++colNum).data().toString();
        QString shortname = proxyModel->index(index.row(), ++colNum).data().toString();
        QString command = proxyModel->index(index.row(), ++colNum).data().toString();
        // QString command = proxyModel->index(index.row(), 4).data().toString();
        qDebug() << "TableView-onSelectedRow-目前过滤剩余: " <<proxyModel->rowCount()<<"条记录";
        qDebug() << "TableView-onSelectedRow-选中行: " << frequency << ", " << shortcut<< ", " << shortname<< ", " << command;
        QStringList strList;
        strList<<encoding;
        CommandExecutor* executor = new CommandExecutor;
        executor->executeCommand(command,strList);
        //处理选中的行 方法二
        // QModelIndex sourceIndex = proxyModel->mapToSource(index);
        // frequency = model->index(sourceIndex.row(), 0).data().toString();
        // shortcut = model->index(sourceIndex.row(), 1).data().toString();
        // shortname = model->index(sourceIndex.row(), 2).data().toString();
        // command = model->index(sourceIndex.row(), 3).data().toString();
        // qDebug() << "Selected: " << frequency << ", " << shortcut<< ", " << shortname<< ", " << command;
    }
}


/**
 * 通过proxyModel过滤QTableView显示数据
 * @brief Widget::filterData
 * @param text
 */
void CustomTableView::filterData(CustomSortFilterProxyModel *proxyModel,QStandardItemModel* itemModel,const QString &text)
{
    // 创建过滤器
    proxyModel->setSourceModel(itemModel);

    // 设置过滤规则
    proxyModel->setFilterRegExp(QRegExp(text, Qt::CaseInsensitive, QRegExp::FixedString));
    //设置模型中的第二列为过滤列
    proxyModel->setFilterKeyColumn(4);

    // 设置表格视图的模型为过滤器
    this->setModel(proxyModel);
}


/**
 * QTableView 的 model() 方法返回当前设置的模型
 * @brief CustomTableView::SelectFirstRow
 */
void CustomTableView::selectFirstRow1()
{
    if (model() && model()->rowCount() > 0) {
        QModelIndex firstIndex = model()->index(0, 0);// 获取代理模型中第一项的索引
        selectionModel()->setCurrentIndex(firstIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);// 选中firstIndex行
        // this->selectRow(firstIndex.row()); // 选中firstIndex行
    }
}

void CustomTableView::selectFirstRow2(){

}

void CustomTableView::selectFirstRow3()
{
     qDebug() << "selectFirstRow->当搜索框内容变化时检查QTableView中的过滤结果是否只有一条记录: ";
    //当搜索框内容变化时检查QTableView中的过滤结果是否只有一条记录
    if (model()->rowCount() == 1) {
        QModelIndex row4 = model()->index(0, 3); // 第四列
        QModelIndex row5 = model()->index(0, 4); // 第五列
        QString row4Val = model()->data(row4).toString();
        QString row5Val = model()->data(row5).toString();
        qDebug() << "QTableView只剩最后一项: " << row4Val<<","<<row5Val;
    }
    //model()方法返回与QTableView关联的QAbstractItemModel对象(负责管理和存储数据)
    QModelIndex firstIndex = model()->index(0, 0); // 获取代理模型中第一项的索引
    this->selectRow(firstIndex.row()); // 选中第一行
    QModelIndexList selectedIndexes = this->selectionModel()->selectedIndexes();

    //selectionModel()方法返回与QTableView关联的QItemSelectionModel对象。选择模型（Selection Model）负责管理视图中项目的选中状态。
    //通过选择模型，你可以获取当前选中的项目，监听选中状态的变化，并进行相应的操作。
    /*if (model() && model()->rowCount() > 0) {
        QModelIndex firstIndex = model()->index(0, 0);
        //设置选中该索引所在的行
        selectionModel()->setCurrentIndex(firstIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);
    }
    */
    /*
        connect(tableView->selectionModel(), &QItemSelectionModel::selectionChanged,[](const QItemSelection &selected, const QItemSelection &deselected) {
            // 处理选中状态变化的逻辑
        });
    */
}
